﻿using System;
using System.Linq;
using System.Diagnostics;
using System.Windows.Forms;
using ResumeSharp.Properties;
using ResumeSharp.Data;

namespace ResumeSharp
{
    public partial class MainForm : Form
    {
        private UserProfileForm myProfile;
        private LocationManager locationMgr;
        private Account user;

        internal ResumeSharpEntities Database { get; set; }

        public MainForm()
        {
            InitializeComponent();
            Database = new ResumeSharpEntities();
            user = this.GetCurrentUser();
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void mnuCascade_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }
        private void mnuTileHorizontal_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileHorizontal);
        }
        private void mnuTileVertical_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileVertical);
        }
        private void mnuCloseAllWin_Click(object sender, EventArgs e)
        {
            foreach (Form f in this.MdiChildren)
                f.Close();
        }
        private void mnuHelpWebsite_Click(object sender, EventArgs e)
        {
            Process.Start(Resources.GEN_HELP_URL);
        }
        private void mnuMyProfile_Click(object sender, EventArgs e)
        {
            if (myProfile == null || myProfile.IsDisposed)
                myProfile = new UserProfileForm(ref user);

            myProfile.MdiParent = this;
            myProfile.StartPosition = FormStartPosition.CenterScreen;
            myProfile.Show();
        }
        private void mnuLocations_Click(object sender, EventArgs e)
        {
            if (locationMgr == null || locationMgr.IsDisposed)
                locationMgr = new LocationManager(ref user);

            locationMgr.MdiParent = this;
            locationMgr.StartPosition = FormStartPosition.CenterScreen;
            locationMgr.Show();
        }


        private Account GetCurrentUser()
        {
            string logon = Utilities.GetLogonId();
            var acctList = from acct in Database.Account where acct.LogonId == logon select acct;

            int numAccounts = acctList.Count();
            if (numAccounts > 1)
                throw new ArgumentOutOfRangeException(Errors.ACCT_TOO_MANY);

            if (acctList.Count() == 1)
                return acctList.First();
            else
                return new Account()
                {
                    LogonId = logon,
                    IsNew = true
                };
        }
    }
}
